package com.zhangqiancheng.wcdmaconsole;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.ProtocalAndUdp.ExcelReader;
//import com.ProtocalAndUdp.ExcelReader;
import com.ProtocalAndUdp.FileOpenerDialog;
import com.ProtocalAndUdp.MyDialogListener;
import com.ProtocalAndUdp.ReadWriteFile;
import com.ProtocalAndUdp.XlsOperate;
import com.zhangqiancheng.wcdmaconsole.db.DbHelper;

public class InputActivity extends Activity {

	SQLiteDatabase db;
	Map<String, Object> item;
	ArrayList<Map<String, Object>> data;
	SimpleAdapter listAdapter;
	ListView listview;
	private int currentId;

	private OnClickListener addButtonOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {

			dbAdd();
		}
	};

	private OnClickListener updateButtonOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			dbUpdate();
		}
	};

	private OnClickListener cancelButtonOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			cancel();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_input);
		listview = (ListView) findViewById(R.id.listView);
		listview.addHeaderView(
				LayoutInflater.from(this).inflate(R.layout.listview_header,
						null), null, false);
		data = new ArrayList<Map<String, Object>>();
		db = DbHelper.getInstance(this, DbHelper.DATABASE_NAME, null,
				DbHelper.DATABASE_VERSION).getWritableDatabase();
		Button btInput = ((Button) findViewById(R.id.btOut));
		btInput.setOnClickListener(addButtonOnClickListener);
		dbSelectAll();
		listview.setOnCreateContextMenuListener(listviewContextMenuListener);
	}

	public void onManyClick(View view) {
		startActivityForResult(new Intent(getApplicationContext(),
				DrectoryList.class), 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 1) {
			//
			String excelPath = data.getData().toString();
			// 读取excel内容
			List<List<String>> source=new ArrayList<List<String>>();
			try {
				source = ExcelReader.readExcel(excelPath);
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 将数据插入数据库
			dbAddMany(source);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void dbAddMany(List<List<String>> source) {
		try{
			for (int i = 1; i < source.size(); i++) {//第0行为标题
				ContentValues values = new ContentValues();
				values.put("imsi", source.get(i).get(0));
				values.put("imei", source.get(i).get(1));
				values.put("note", source.get(i).get(2));
				long count = db.insert(DbHelper.WATCH_TABLE, null, values);
				if (count <= 0) {
					toast("第"+i+"行数据插入失败！");
					break;
				}
			}
			dbSelectAll();
		}
		catch(Exception ex)
		{
			toast("数据插入失败！");
		}
	}

	private OnCreateContextMenuListener listviewContextMenuListener = new OnCreateContextMenuListener() {
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {

			menu.setHeaderTitle("操作");// 标题
			menu.add(0, R.id.update, 0, "修改");
			menu.add(0, R.id.delete, 0, "删除");
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.input, menu);
		return true;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		ContextMenuInfo info = item.getMenuInfo();
		AdapterView.AdapterContextMenuInfo contextMenuInfo = (AdapterView.AdapterContextMenuInfo) info;
		// 获取选中行位置
		int position = contextMenuInfo.position;
		// 注意：由于多了一行标题，这里的 position 需要减 1
		Map<String, Object> oneItem = (Map<String, Object>) listAdapter
				.getItem(position - 1); // data.get(position);
		currentId = Integer.parseInt(oneItem.get("id").toString());
		if (item.getItemId() == R.id.update) {
			((EditText) findViewById(R.id.etIMEI)).setText(oneItem.get("imei")
					.toString());
			((EditText) findViewById(R.id.etIMSI)).setText(oneItem.get("imsi")
					.toString());
			((EditText) findViewById(R.id.etNote)).setText(oneItem.get("note")
					.toString());
			changeButtonState(true);
		} else {
			dbDelete(currentId);
		}
		refreshListView();
		return super.onContextItemSelected(item);
	}

	private void changeButtonState(boolean editState) {
		Button btnInput = (Button) findViewById(R.id.btOut);
		Button btnCancel = (Button) findViewById(R.id.btStop);

		// 编辑状态，左边2个按钮变化，否则恢复到输入状态
		if (editState) {
			btnInput.setText("修改");
			btnInput.setOnClickListener(updateButtonOnClickListener);
			btnCancel.setText("撤销");
			btnCancel.setOnClickListener(cancelButtonOnClickListener);
		} else {
			btnInput.setText("输入");
			btnInput.setOnClickListener(addButtonOnClickListener);
			btnCancel.setText("");
			btnCancel.setOnClickListener(null);
			currentId = 0;
			clearTextEdit();
		}

	}

	public void backButtonClick(View view) {
		onBackPressed();
	}

	// public void ManyInputClick(View view) {
	//
	// }

	private long dbAdd() {
		String imei = ((EditText) findViewById(R.id.etIMEI)).getText()
				.toString();
		String imsi = ((EditText) findViewById(R.id.etIMSI)).getText()
				.toString();
		if (imei.equals("")) {
			alert("请填写IMEI！");
			return -1;
		}
		if (imsi.equals("")) {
			alert("请填写IMSI！");
			return -1;
		}
		ContentValues values = new ContentValues();
		values.put("imei", imei);
		values.put("imsi", imsi);
		values.put("note", ((EditText) findViewById(R.id.etNote)).getText()
				.toString());
		long count = db.insert(DbHelper.WATCH_TABLE, null, values);
		if (count <= 0)
			toast("数据插入失败！");
		else {
			if (count != -1) {
				// 清空记录
				clearTextEdit();
				toast("数据插入成功！");
				try {
					ReadWriteFile.writeTxtFile(this, "名单库增加记录");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			refreshListView();
		}
		return count;
	}

	private void clearTextEdit() {
		((EditText) findViewById(R.id.etIMEI)).setText("");
		((EditText) findViewById(R.id.etIMSI)).setText("");
		((EditText) findViewById(R.id.etNote)).setText("");
	}

	private void cancel() {
		changeButtonState(false);
	}

	private void refreshListView() {
		data.clear();
		dbSelectAll();
	}

	private void alert(String message) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(android.R.drawable.btn_star);
		builder.setMessage(message);
		builder.setTitle("警告");
		android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {

				arg0.dismiss();
			}
		};
		builder.setPositiveButton("确认", listener);
		builder.create().show();
	}

	private void dbDelete(int id) {
		int i = db.delete(DbHelper.WATCH_TABLE,
				String.format("%s = %d", DbHelper.KEY_ID, currentId), null);
		if (i > 0) {
			toast("数据删除成功！");
			try {
				ReadWriteFile.writeTxtFile(this, "名单库删除记录");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			toast("数据删除失败！");
		}
	}

	private void toast(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
				.show();
	}

	private void dbUpdate() {
		ContentValues values = new ContentValues();
		values.put("imei", ((EditText) findViewById(R.id.etIMEI)).getText()
				.toString());
		values.put("imsi", ((EditText) findViewById(R.id.etIMSI)).getText()
				.toString());
		values.put("note", ((EditText) findViewById(R.id.etNote)).getText()
				.toString());
		String where = String.format("%s=%d", DbHelper.WCDMA_TABLE, currentId);
		int i = db.update(DbHelper.WATCH_TABLE, values, where, null);
		if (i > 0) {
			toast("数据更新成功！");
			changeButtonState(false);
			refreshListView();
			try {
				ReadWriteFile.writeTxtFile(this, "名单库修改记录");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			toast("数据更新失败！");
		}
	}

	private void dbSelectAll() {
		data.clear();
		Cursor cursor = db.query(DbHelper.WATCH_TABLE, null, null, null, null,
				null, DbHelper.KEY_ID_ASC);
		try {
			while (cursor.moveToNext()) {
				String id = cursor.getString(0);
				String imsi = cursor.getString(1);
				String imei = cursor.getString(2);
				String note = cursor.getString(3);
				addItemToData(id, imsi, imei, note);
			}
			showList();
		} finally {
			cursor.close();
		}
	}

	private void addItemToData(String id, String IMSI, String IMEI, String note) {
		item = new HashMap<String, Object>();
		item.put("id", id);
		item.put("imsi", IMSI);
		item.put("imei", IMEI);
		item.put("note", note);
		data.add(item);
	}

	private void showList() {
		listAdapter = new SimpleAdapter(this, data, R.layout.listview,
				new String[] { "imsi", "imei", "note" }, new int[] {
						R.id.tvItemIMSI, R.id.tvItemIMEI, R.id.tvItemNote });
		listview.setAdapter(listAdapter);
	}

	// @Override
	// public void OnOkClick(String result) {
	//
	// // 导入数据
	// }
}
